package com.example.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.train.business.domain.Daily_Train;
import com.example.train.business.domain.Daily_TrainTicket;
import com.example.train.business.domain.Daily_TrainTicketExample;
import com.example.train.business.domain.Train_Station;
import com.example.train.business.enums.SeatTypeEnum;
import com.example.train.business.enums.TrainTypeEnum;
import com.example.train.business.mapper.Daily_TrainTicketMapper;
import com.example.train.business.req.Daily_TrainTicketQueryReq;
import com.example.train.business.req.Daily_TrainTicketSaveReq;
import com.example.train.business.resp.Daily_TrainTicketQueryResp;
import com.example.train.common.resp.PageResp;
import com.example.train.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class Daily_TrainTicketService {
    private static final Logger LOG = LoggerFactory.getLogger(Daily_TrainTicketService.class);

    @Resource
    private Daily_TrainTicketMapper daily_TrainTicketMapper;

    @Resource
    private Train_StationService train_stationService;
    @Autowired
    private Daily_TrainSeatService daily_TrainSeatService;

    /**
     * 乘客注册请求的服务类，在这个类中不会被用到
     * @param req
     */
    public void save(Daily_TrainTicketSaveReq req) {
        DateTime now = DateTime.now();
        Daily_TrainTicket daily_TrainTicket = BeanUtil.copyProperties(req, Daily_TrainTicket.class);
        if(ObjectUtil.isNull(daily_TrainTicket.getId())){
            //在service中对以下三种数据赋值，因为请求参数不带这三个值，需要服务端自行设置
            daily_TrainTicket.setId(SnowUtil.getSnowflakeNextId());
            daily_TrainTicket.setCreateTime(now);
            daily_TrainTicket.setUpdateTime(now);
            daily_TrainTicketMapper.insert(daily_TrainTicket);
        }else{
            daily_TrainTicket.setUpdateTime(now);
            daily_TrainTicketMapper.updateByPrimaryKey(daily_TrainTicket);
        }
    }
    public PageResp<Daily_TrainTicketQueryResp> queryList(Daily_TrainTicketQueryReq req) {
        Daily_TrainTicketExample daily_TrainTicketExample = new Daily_TrainTicketExample();
        daily_TrainTicketExample.setOrderByClause("date asc,id desc");
        Daily_TrainTicketExample.Criteria criteria = daily_TrainTicketExample.createCriteria();
        if (ObjUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }
        if (ObjUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }
        if (ObjUtil.isNotEmpty(req.getStart())) {
            criteria.andStartEqualTo(req.getStart());
        }
        if (ObjUtil.isNotEmpty(req.getEnd())) {
            criteria.andEndEqualTo(req.getEnd());
        }

        LOG.info("查询页码是 {}", req.getPage());
        LOG.info("每页条数是 {}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Daily_TrainTicket> daily_TrainTicketList = daily_TrainTicketMapper.selectByExample(daily_TrainTicketExample);

        PageInfo<Daily_TrainTicket> pageInfo = new PageInfo<>(daily_TrainTicketList);
        LOG.info("总行数是 {}", pageInfo.getTotal());
        LOG.info("总页数是 {}", pageInfo.getPages());

        List<Daily_TrainTicketQueryResp> list = BeanUtil.copyToList(daily_TrainTicketList, Daily_TrainTicketQueryResp.class);

        PageResp<Daily_TrainTicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 删除乘客信息的服务实现
     * @param id
     */
    public void delete(Long id) {
        daily_TrainTicketMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public void genDaily(Daily_Train daily_Train, Date date, String trainCode){

        LOG.info("生成日期【{}】车次【{}】的余票信息开始", DateUtil.formatDate(date), trainCode);

        //删除当前存在的车票信息
        Daily_TrainTicketExample  daily_trainTicketExample = new Daily_TrainTicketExample();
        daily_trainTicketExample.createCriteria().andDateEqualTo(date).andTrainCodeEqualTo(trainCode);
        daily_TrainTicketMapper.deleteByExample(daily_trainTicketExample);

        // 查出某车次的所有的车站信息
        List<Train_Station> stationList = train_stationService.selectByTrainCode(trainCode);
        if (CollUtil.isEmpty(stationList)) {
            LOG.info("该车次没有车站基础数据，生成该车次的余票信息结束");
            return;
        }

        DateTime now = DateTime.now();
        int ydz=daily_TrainSeatService.countSeat(date,trainCode, SeatTypeEnum.YDZ.getCode());
        int edz=daily_TrainSeatService.countSeat(date,trainCode, SeatTypeEnum.EDZ.getCode());
        int rw=daily_TrainSeatService.countSeat(date,trainCode, SeatTypeEnum.RW.getCode());
        int yw=daily_TrainSeatService.countSeat(date,trainCode, SeatTypeEnum.YW.getCode());
        for (int i = 0; i < stationList.size(); i++) {
            Train_Station train_stationStart = stationList.get(i);
            BigDecimal sumKM = BigDecimal.ZERO;
            for (int j = i+1; j <stationList.size() ; j++) {
                Train_Station train_stationEnd = stationList.get(j);
                sumKM = sumKM.add(train_stationEnd.getKm());

                Daily_TrainTicket daily_TrainTicket = new Daily_TrainTicket();

                daily_TrainTicket.setId(SnowUtil.getSnowflakeNextId());
                daily_TrainTicket.setDate(date);
                daily_TrainTicket.setTrainCode(trainCode);
                daily_TrainTicket.setStart(train_stationStart.getName());
                daily_TrainTicket.setStartPinyin(train_stationStart.getNamePinyin());
                daily_TrainTicket.setStartTime(train_stationStart.getOutTime());
                daily_TrainTicket.setStartIndex(train_stationStart.getIndex());
                daily_TrainTicket.setEnd(train_stationEnd.getName());
                daily_TrainTicket.setEndPinyin(train_stationEnd.getNamePinyin());
                daily_TrainTicket.setEndTime(train_stationEnd.getInTime());
                daily_TrainTicket.setEndIndex(train_stationEnd.getIndex());

                //火车票价=总里程*火车类型系数*车座类型系数
                String trainType = daily_Train.getType();

                BigDecimal priceRate = EnumUtil.getFieldBy(TrainTypeEnum::getPriceRate, TrainTypeEnum::getCode, trainType);
                BigDecimal ydzPrice = sumKM.multiply(SeatTypeEnum.YDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal edzPrice = sumKM.multiply(SeatTypeEnum.EDZ.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal rwPrice = sumKM.multiply(SeatTypeEnum.RW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);
                BigDecimal ywPrice = sumKM.multiply(SeatTypeEnum.YW.getPrice()).multiply(priceRate).setScale(2, RoundingMode.HALF_UP);

                daily_TrainTicket.setYdz(ydz);
                daily_TrainTicket.setEdz(edz);
                daily_TrainTicket.setRw(rw);
                daily_TrainTicket.setYw(yw);

                if(ydz==-1){
                    daily_TrainTicket.setYdzPrice(BigDecimal.ZERO);

                }else{
                    daily_TrainTicket.setYdzPrice(ydzPrice);
                }
                if(edz==-1){
                    daily_TrainTicket.setEdzPrice(BigDecimal.ZERO);

                }else{
                    daily_TrainTicket.setEdzPrice(edzPrice);
                }
                if(yw==-1){
                    daily_TrainTicket.setYwPrice(BigDecimal.ZERO);

                }else{
                    daily_TrainTicket.setYwPrice(ywPrice);
                }
                if(rw==-1){
                    daily_TrainTicket.setRwPrice(BigDecimal.ZERO);

                }else{
                    daily_TrainTicket.setRwPrice(rwPrice);
                }
                daily_TrainTicket.setCreateTime(now);
                daily_TrainTicket.setUpdateTime(now);
                daily_TrainTicketMapper.insert(daily_TrainTicket);

            }

        }
        LOG.info("生成日期【{}】车次【{}】的余票信息结束", DateUtil.formatDate(date), trainCode);

    }

    /**
     * 通过唯一键来检索信息
     * @param date
     * @param trainCode
     * @param start
     * @param end
     * @return
     */
    public Daily_TrainTicket selectByUnique(Date date, String trainCode, String start, String end) {
        Daily_TrainTicketExample dailyTrainTicketExample = new Daily_TrainTicketExample();
        dailyTrainTicketExample.createCriteria()
                .andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andStartEqualTo(start)
                .andEndEqualTo(end);
        List<Daily_TrainTicket> list = daily_TrainTicketMapper.selectByExample(dailyTrainTicketExample);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }


}
